package com.coderdream.chapter09.bridge.a2;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileDisplayImpl extends DisplayImpl {

	private String filename;

	private BufferedReader reader;

	private final int MAX_READAHEAD_LIMIT = 4096;

	// 可反復打印的上限（緩沖器容量）
	public FileDisplayImpl(String filename) {
		this.filename = filename;
	}
	

	@Override
	public void rawOpen() {
		try {
			reader = new BufferedReader(new FileReader(filename));
			reader.mark(MAX_READAHEAD_LIMIT);
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 花邊
		System.out.println("=-=-=-=-=  " + filename + "  =-=-=-=-=");
	}

	@Override
	public void rawPrint() {
		try {
			String line;
			reader.reset(); // 返回到 mark 的位置
			
			while ((line = reader.readLine()) != null) {
				System.out.println(">" + line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void rawClose() {
		System.out.println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); // 花邊
		
		try {
			reader.close(); // 返回到 mark 的位置

		} catch (IOException e) {
			e.printStackTrace();
		}

	}


}
